//
//  GuiderViewController.m
//  kankanVideo
//
//  Created by wangbo on 5/22/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "GuiderViewController.h"
#import "Reachability.h"
#import "ASIHTTPRequest.h"
#import "ASIDownloadCache.h"
#import "GuiderXMLParser.h"
#import "XMLParser.h"
//#import "IndexViewController.h"
#import "MyRequest.h"
#import "AppDelegate.h"
#import "GANTracker.h"

static NSString *guiderurl=@"http://interface.kankanews.com/kkapi/mobile/padapi.php?m=index";
static NSString *gg=@"http://static.statickksmg.com/image/2012/05/04/2ce90c03000949471a699c6488931f57.jpg";
@implementation GuiderViewController
@synthesize imageView;
@synthesize btnIndex;
//@synthesize index;
@synthesize zy;
//@synthesize asirequest;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

-(void) dealloc{
    [imageView release];
    [btnIndex release];
    //[index release];
    [zy release];
    //[asirequest release];
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    NSLog(@"recieivememorywaning");
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    // Reachability. 
    NSLog(@"guider_viewdidload");
    NSArray* _arr=[[MyCoreData shareInstance]queryConfig];
    if (_arr.count==0) {
        if (!hvc) {
            hvc=[[[HelperVierController alloc]init]autorelease];
        }
        [self presentModalViewController:hvc animated:NO];
        [[MyCoreData shareInstance]insertConfig:@"yes"];
    }
    
    status=0;
    //[self loaddata:guiderurl];
    //MyRequest *myrequest=[[[MyRequest alloc]init] autorelease];
    //BOOL isconnected=[myrequest checkNetwork];
    BOOL isconnected=[[MyRequest shareInstance]checkNetwork];
    if(isconnected){
        [[MyRequest shareInstance]loaddataWithURL:guiderurl forObject:self];
        //[myrequest loaddataWithURL:guiderurl forObject:self];
        imageView.image=[UIImage imageNamed:@"zhuye_bj.jpg"];
        /*UISwipeGestureRecognizer *recegnizer=[[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(swipeHandler:)];
        [recegnizer setDirection:UISwipeGestureRecognizerDirectionLeft];
        [self.view addGestureRecognizer:recegnizer];
        [recegnizer release];*/
    }else{
        imageView.image=[UIImage imageNamed:@"zhuye_bj.jpg"];
        AppDelegate *app=(AppDelegate *)[[UIApplication sharedApplication]delegate];
        [app showAlert:@"网络故障"];
        [btnIndex setEnabled:NO];
        [self performSelector:@selector(reconnect) withObject:nil afterDelay:5];
    }
}

-(void)reconnect{
    MyRequest *myrequest=[[[MyRequest alloc]init] autorelease];
    BOOL isconnected=[myrequest checkNetwork];
    if(isconnected){
        AppDelegate *app=(AppDelegate *)[[UIApplication sharedApplication]delegate];
        [app hideAlert];
        [[MyRequest shareInstance] loaddataWithURL:guiderurl forObject:self];
        /*UISwipeGestureRecognizer *recegnizer=[[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(swipeHandler:)];
        [recegnizer setDirection:UISwipeGestureRecognizerDirectionLeft];
        [self.view addGestureRecognizer:recegnizer];
        [recegnizer release];*/
    }else{
        [self performSelector:@selector(reconnect) withObject:nil afterDelay:5];
    }
}


-(void)viewWillAppear:(BOOL)animated{
        NSError *error;
        if (![[GANTracker sharedTracker] trackPageview:@"看看吧ipad-启动页"
                                             withError:&error]) {
            NSLog(@"error in trackPageview");
        }
        NSLog(@"guilder_view_will_appear");
    NSLog(@"guilder_view_will_appear");
}

-(void)swipeHandler:(UISwipeGestureRecognizer*)recognizer{
    //[self.navigationController popViewControllerAnimated:YES];
    [self btnIndex_click:nil];
}

-(void)loaddata:(NSString *)weburl{
    //NSLog(@"%@",weburl);
    //[request startAsynchronous];
}
-(IBAction)btnIndex_click:(id)sender{
    /*if(!index)index=[[IndexViewController alloc]init];
    [self.navigationController pushViewController:index animated:YES];*/
    //AppDelegate *app=(AppDelegate *)[[UIApplication sharedApplication]delegate];
    //if (!app.zyViewController) {
      //  app.zyViewController=[[zhuye alloc]init];
    //}
    if(!zy)zy=[[zhuye alloc]init];
    //if(!zy)zy=[[IndexViewController alloc]init];
    [self.navigationController pushViewController:zy animated:YES];
}

-(void)requestFinishedHandler:(ASIHTTPRequest*)request{
    if(request.responseStatusCode==200){
        [btnIndex setEnabled:YES];
        if(status==0){
            NSMutableArray *dict=[XMLParser parseGuiderXML:request.responseData];
            //status=1;
            //MyRequest *myrequest=[[[MyRequest alloc]init] autorelease];
            //[myrequest loaddataWithURL:[dict objectAtIndex:0] forObject:self];
            int i0=arc4random()%10+1;
            int i1=arc4random()%10+1;
            if(i1==i0)i1=i0+1;
            if(i1==11)i1=1;
            i0=i0-1;
            i1=i1-1;
            NSLog(@"fengmian_index:%d and %d:",i0,i1);
            NSLog(@"pic1:%@",[dict objectAtIndex:i0]);
            NSLog(@"pic2:%@",[dict objectAtIndex:i1]);
            status=1;
            url0=[dict objectAtIndex:i0];
            url1=[dict objectAtIndex:i1];
            [[MyRequest shareInstance]loaddataWithURL:url0 forObject:self];
            NSLog(@"requestFinishtedHandler");
        }else if(status==1){
            //UIImage *image=[UIImage imageWithData:request.responseData];
            NSLog(@"url1:%@",url1);
            img0=[UIImage imageWithData:request.responseData];
            [img0 retain];
            status=2;
            [[MyRequest shareInstance]loaddataWithURL:url1 forObject:self];
        }else if(status==2){
            img1=[UIImage imageWithData:request.responseData];
            [img1 retain];
            status=0;
            [self showPic];
        }
    }
}
-(void)showPic{
    //UIImage *img0=[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[dict objectAtIndex:i0]]]];
    //UIImage *img1=[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[dict objectAtIndex:i1]]]];
    imageView.animationImages=[NSArray arrayWithObjects:img0,img1, nil];
    imageView.animationDuration=5;
    imageView.animationRepeatCount=0;
    [imageView startAnimating];
    //[self performSelector:@selector(btnIndex_click:) withObject:nil afterDelay:10];
}
-(void)requestFailedHandler:(ASIHTTPRequest *)request{
    NSError *err=request.error;
    NSLog(@"%@",err);
    NSLog(@"failed");
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationLandscapeRight||interfaceOrientation==UIInterfaceOrientationLandscapeLeft);
}

@end
